package com.meeting.interceptor;

import com.meeting.utils.JWTUtil;
import com.meeting.utils.UserContext;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");

        if(token == null || token.isBlank()){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.info("无令牌，无法通行");
            return false;
        }

        try {
            log.info("解析令牌");
            Claims claims = JWTUtil.parseToken(token);
            log.info("解析成功");
            Integer id = claims.get("id",Integer.class);
            String role = claims.get("role",String.class);
            System.out.println(role);

            String uri = request.getRequestURI();
            if(uri.startsWith("/admin") && !"admin".equals(role)){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                log.info("无管理员权限，无法通行");
                return false;
            }
            if(uri.startsWith("/user") && !"user".equals(role)){
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                log.info("无用户权限，无法通行");
                return false;
            }

            //将内容存入上下文
            UserContext.setId(id);
            UserContext.setRole(role);

            return true;
        }catch (Exception e){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.info("令牌解析失败，无法通行");
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear();
    }
}
